package com.baiduspring.service.virtualnum.impl;

import com.baiduspring.dao.entity.VirtualNumber;
import com.baiduspring.dao.mapper.VirtualNumberMapper;
import com.baiduspring.service.virtualnum.VirtualNumberService;
import com.google.common.base.Preconditions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class VirtualNumberServiceImpl implements VirtualNumberService {
    @Resource
    private VirtualNumberMapper virtualNumberMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long getVirtualNumber() {
        VirtualNumber virtualNumber = virtualNumberMapper.selectByPrimaryKey(1L);
        Preconditions.checkArgument(Objects.nonNull(virtualNumber), "虚拟号码数据为null");

        if (Objects.isNull(virtualNumber.getCurrentValue())) {
            this.update(() -> virtualNumberMapper.updateByPrimaryKeySelective(virtualNumber.update()));
            return virtualNumber.getMinValue();
        }

        if (virtualNumber.getCurrentValue() < virtualNumber.getMaxValue()) {
            this.update(() -> virtualNumberMapper.update(virtualNumber.update()));
            return virtualNumberMapper.selectByPrimaryKey(1L).getCurrentValue();
        }

        return null;
    }

    private void update(UpdateCurrentValue updateCurrentValue) {
        updateCurrentValue.update();
    }

    interface UpdateCurrentValue {
        void update();
    }
}
